package utils

import (
	"errors"
	"time"

	"github.com/dgrijalva/jwt-go/v4"
	"github.com/spf13/viper"
)

// 多次使用select
type JwtCustClaims struct {
	ID   int
	NAME string
	jwt.StandardClaims
}

var signedKey []byte //!注意

// settime : 获取viper中设定的时间
func GenerateJwt(id int, name string, settime string) (string, error) {
	customClaims := JwtCustClaims{
		ID:   id,
		NAME: name,
		StandardClaims: jwt.StandardClaims{
			// ExpiresAt: jwt.At(time.Now().Add(0)),
			ExpiresAt: jwt.At(time.Now().Add(time.Hour * viper.GetDuration(settime))),
			Subject:   "token",
		},
	}
	//生成配置
	generator := jwt.NewWithClaims(jwt.SigningMethodHS256, customClaims)
	if len(signedKey) == 0 {
		signedKey = []byte(viper.GetString("jwt.select"))
	}
	return generator.SignedString(signedKey)
}

// 解析token
func DecodeJwt(token string) (JwtCustClaims, error) {
	if len(signedKey) == 0 {
		signedKey = []byte(viper.GetString("jwt.select"))
	}
	receive := JwtCustClaims{}
	decode, err := jwt.ParseWithClaims(token, &receive, func(t *jwt.Token) (interface{}, error) {
		return signedKey, nil
	})
	if err == nil && !decode.Valid {
		err = errors.New("Invalid token")
	}
	return receive, err
}

// 校验token
func ValidJwt(token string) bool {
	_, err := DecodeJwt(token)
	if err != nil {
		return false
	} else {
		return true
	}
}
